package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 订单提交
     * @param orders
     */
    @Override
    @Transactional
    public void postOrders(Orders orders) {
        /**
         * 订单信息存储
         */
        // 获取用户信息
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);
        // 获取收货地址信息
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId).eq(AddressBook::getId,orders.getAddressBookId());
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        // 判断地址是否为空
        if (addressBook == null){
            throw new CustomException("收货地址不能为空!");
        }
        // 获取购物车信息
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper1);
        // 判断购物车是否为空
        if (shoppingCartList == null){
            throw new CustomException("请先添加商品!");
        }
        // 获取订单号
        Long ordersId = IdWorker.getId();
        // 创建总金额变量
        AtomicInteger amount = new AtomicInteger(0);//AtomicInteger: 可以再多线程情况下保证线程安全,因为这个是原子操作

        // 获取总金额和订单明细集合
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            // 计算总金额
            /** AtomicInteger使用说明
             *     AtomicInteger atomicInteger = new AtomicInteger(10);
             * addAndGet: 先对atomicInteger进行加法,再对atomicInteger进行查询
             *         int andGet = atomicInteger.addAndGet(20);
             *         System.out.println(atomicInteger);   // 30
             *         System.out.println(andGet);          // 30
             *----------------------------------------------------------------------------
             *     AtomicInteger atomicInteger = new AtomicInteger(10);
             * getAndAdd: 先对atomicInteger进行查询,再对atomicInteger进行加法
             *         int andAdd = atomicInteger.getAndAdd(20);
             *         System.out.println(atomicInteger);   // 30
             *         System.out.println(andAdd);          // 10
             *----------------------------------------------------------------------------
             *      AtomicInteger接收参数: int类型
             *      shoppingCart.getAmount(): 购物车单条数据的商品金额
             *      multiply: BigDecimal类型的乘法(实体类的金额类型为BigDecimal)
             *      new BigDecimal(shoppingCart.getNumber()): 购物车单条数据商品的数量
             *      intValue(): 将BigDecimal类型转换为int类型
             */
            amount.addAndGet((shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()))).intValue());

            // 订单明细
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);  // 拷贝购物车信息
            orderDetail.setOrderId(ordersId);                    // 设置订单id
            orderDetailList.add(orderDetail);
        }
        // 设置订单信息
        orders.setId(ordersId);
        orders.setNumber(ordersId.toString());          //设置订单号
        orders.setStatus(2);                            //设置订单状态
        orders.setUserId(userId);                       //设置下单用户id
        orders.setAddressBookId(addressBook.getId());   //设置收货地址id
        orders.setOrderTime(LocalDateTime.now());       //设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());    //设置结账时间
        orders.setAmount(new BigDecimal(amount.get())); //设置实收金额
        orders.setUserName(user.getName());             //设置用户名
        orders.setPhone(addressBook.getPhone());        //设置收货人手机
        orders.setAddress(addressBook.getDetail());     //设置收货地址
        orders.setConsignee(addressBook.getConsignee());//设置收货人


        /**
         * 订单表和订单明细表数据设置(老师的方法)
        //组装订单明细信息
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(ordersId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new
                    BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //组装订单数据
        orders.setId(ordersId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(ordersId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" :
                addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" :
                addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
         */
        // 订单存储
        this.save(orders);
        // 订单明细存储
        orderDetailService.saveBatch(orderDetailList);
        // 购物车清空
        shoppingCartService.remove(queryWrapper1);
    }


    /**
     * 订单查询
     * @param page  分页页码
     * @param pageSize  分页条数
     * @return
     */
    @Override
    public Page<OrderDto> showAllOrder(Long page, Long pageSize) {
        // 获取下单用户id
        Long userId = BaseContext.getCurrentId();
        // 分页构造器
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        // 设置排序(降序,最新时间)
        queryWrapper.orderByDesc(Orders::getOrderTime);
        // 执行查询
        this.page(ordersPage,queryWrapper);
        // 数据拷贝(拷贝后,Page<OrderDto>中就只差records了,records是封装OrderDto数据集合的)
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");
        // 获取Orders集合
        List<Orders> records = ordersPage.getRecords();
        // 创建OrderDto集合,准备接收数据
        List<OrderDto> result = new ArrayList<>();
        // 封装每一条OrderDto数据
        for (Orders record : records) {         // 遍历订单集合
            OrderDto orderDto = new OrderDto();     // 创建OrderDto对象
            BeanUtils.copyProperties(record,orderDto);  // 将单挑订单数据拷贝到OrderDto实体类中,这样OrderDto实体类就只差订单明细集合了
            // 获取订单id
            Long id = record.getId();
            //查询订单明细集合
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> list = orderDetailService.list(queryWrapper1);
            //将订单明细集合存入OrderDto中
            orderDto.setOrderDetails(list);
            // 将封装好的OrderDetail实体类添加到集合中
            result.add(orderDto);
        }
        // 将OrderDto集合放入Page<OrderDto>的Records中
        orderDtoPage.setRecords(result);
        return orderDtoPage;
    }

}
